package com.cqhz.quwan.ui.activity

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.esport.ESportDetailContract
import com.cqhz.quwan.mvp.esport.ESportDetailPresenter
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.mvp.mine.AlipayPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.interfaces.SelectTeamItemClickListener
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.main.order.OrderListActivity
import com.cqhz.quwan.ui.widget.dialog.OrderDialog
import com.cqhz.quwan.ui.widget.dialog.PrizeDialog
import com.cqhz.quwan.ui.widget.dialog.RewardDialog
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.json
import com.cqhz.quwan.util.setLoadImage
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_esport_detail.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import javax.inject.Inject

/**
 * 电竞详情
 * Created by Guojing on 2018/10/12.
 */
class ESportDetailActivity : GoBackActivity(), AlipayContract.View, ESportDetailContract.View, HasDaggerInject<ActivityInject>, SelectTeamItemClickListener, OrderDialog.OrderConfirmClickListener {

    @Inject
    lateinit var modelHelper: ModelHelper
    @Inject
    lateinit var alipayPresenter: AlipayPresenter
    @Inject
    lateinit var eSportDetailPresenter: ESportDetailPresenter
    private var titles = arrayOf("总局")
    private var rounds = arrayOf("0")
    private var loginBean: LoginBean? = null
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var guesses = ArrayList<ArrayList<ESportItemBean>>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var eSportDetailBean: ESportDetailBean? = null
    private var dialog: OrderDialog? = null
    private var bean: String = "0"

    companion object {
        const val REQUEST_RECHARGE = 0x1001
    }

    override fun layout(): Int {
        return R.layout.activity_esport_detail
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun initView() {
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }
        alipayPresenter.attachView(this)
        eSportDetailPresenter.attachView(this)

        setTitleBarText(intent.getStringExtra(KeyContract.Title))

        eSportDetailPresenter.getDetailHead(intent.getStringExtra("matchId"))
        if (loginBean != null) {
            eSportDetailPresenter.getUserInfo(loginBean!!.userId!!)
        }
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter() {
        // 当前页面的布局
        var pageView = LayoutInflater.from(this).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据、适配器以及适配器的事件
        var guessList = ArrayList<ESportItemBean>()
        var eSportDetailGuessListAdapter = CommonAdapterHelper.getESportDetailGuessListAdapter(this, guessList, this)
        eSportDetailGuessListAdapter.emptyView = emptyView

        holder.rvContent.layoutManager = LinearLayoutManager(this)
        holder.rvContent.adapter = eSportDetailGuessListAdapter

        // 刷新
        holder.refreshLayout.setOnRefreshListener { refreshCurrentPage() }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        guesses.add(guessList)
        adapters.add(eSportDetailGuessListAdapter)
    }

    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                refreshCurrentPage()
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage() {
        var currentPage = vp_content.currentItem
        eSportDetailPresenter.getGameItemList(currentPage, intent.getStringExtra("matchId"), rounds[currentPage])
    }

    override fun setDetailHead(bean: ESportDetailBean) {
        eSportDetailBean = bean

        iv_host_logo!!.setLoadImage(this, bean.leftTeamLogo, R.drawable.esports_img_default)// 主队logo
        iv_guest_logo!!.setLoadImage(this, bean.rightTeamLogo, R.drawable.esports_img_default)// 副队logo
        tv_host_name.text = bean.leftTeam
        tv_guest_name.text = bean.rightTeam
        tv_game_info.text = bean.matchName
        tv_game_round.text = "BO" + bean.round
        tv_game_score.text = bean.score
        tv_game_status.text = "进行中"

        when {
            bean.betStatus == "0" -> {
                tv_game_status.text = "可预测"
                tv_game_status.setTextColor(Color.parseColor("#FFFFFF"))
                tv_game_status.setBackgroundResource(R.drawable.sp_orange_x12)
            }
            bean.betStatus != "0" && bean.status == "1" -> {
                tv_game_status.text = "进行中"
                tv_game_status.setTextColor(Color.parseColor("#FF513A"))
                tv_game_status.setBackgroundResource(R.drawable.sp_stroke_orange_x12)
            }
            bean.betStatus != "0" && bean.status == "2" -> {
                tv_game_status.text = "已结束"
                tv_game_status.setTextColor(Color.parseColor("#333333"))
                tv_game_status.setBackgroundResource(R.drawable.sp_gray_x12)
            }
            bean.betStatus != "0" && bean.status == "3" -> {
                tv_game_status.text = "已取消"
                tv_game_status.setTextColor(Color.parseColor("#333333"))
                tv_game_status.setBackgroundResource(R.drawable.sp_gray_x12)
            }
            else -> {
                tv_game_status.text = "未开始"
            }
        }
        tv_host_support_rate.text = if (StringUtils.isEmpty(bean.leftSupport)) "50" else bean.leftSupport
        tv_guest_support_rate.text = if (StringUtils.isEmpty(bean.rightSupport)) "50" else bean.rightSupport
        Log.e("setDetailHead：", bean.leftSupport + bean.rightSupport)

        val weight1 = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, (if (StringUtils.isEmpty(bean.leftSupport)) "1" else bean.leftSupport).toFloat() * 100f)
        val weight2 = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, (if (StringUtils.isEmpty(bean.rightSupport)) "1" else bean.rightSupport).toFloat() * 100f)
        iv_middle.visibility = if (bean.leftSupport == "0" || bean.rightSupport == "0") View.GONE else View.VISIBLE
        bt_host_support_rate.layoutParams = weight1
        bt_guest_support_rate.layoutParams = weight2

        // 设置列表页面标题
        if (!StringUtils.isEmpty(bean.rounds)) {
            titles = bean.rounds.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() // 用,分割
            rounds = bean.rounds.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() // 用,分割
            for (i in 0 until rounds.size) {
                // rounds  第几局 0:总局(足球、篮球 全场) 0.5:上半场(足球、篮球) 1.5:下半场(足球、篮球) 1:第一局(篮球第一节)
                // 2:第二局(篮球第二节) 3:第三局(篮球第三节) 4:第四局(篮球第四节) 5:第五局 6:第六局 7:第七局
                // 游戏类型 0:全部 1:LOL 2:DOTA2 3:CSGO 4:守望先锋 5:篮球 6:足球 7:王者荣耀 8:绝地求生 9:魔兽争霸3 10:炉石传说 11:彩虹6号  12:星际争霸1 13:星际争霸2 14:风暴英雄 15:堡垒之夜 16:FIFA Online 17:穿越火线 18:传说对决 19:使命召唤 20:火箭联盟 21:NBA2K'
                when (bean.type) {
                    "5", "21" -> {
                        when (rounds[i]) {
                            "0" -> titles[i] = "全场"
                            "0.5" -> titles[i] = "上半场"
                            "1.5" -> titles[i] = "下半场"
                            "1" -> titles[i] = "第一节"
                            "2" -> titles[i] = "第二节"
                            "3" -> titles[i] = "第三节"
                            "4" -> titles[i] = "第四节"
                            else -> titles[i] = "其他"
                        }
                    }
                    "6", "16" -> {
                        when (rounds[i]) {
                            "0" -> titles[i] = "全场"
                            "0.5" -> titles[i] = "上半场"
                            "1.5" -> titles[i] = "下半场"
                            else -> titles[i] = "其他"
                        }
                    }
                    else -> titles[i] = if (i == 0) "总局" else "局$i"
                }
            }
        }
        setTitleList()
    }

    /**
     * 设置列表页面标题
     */
    private fun setTitleList() {
        // 初始化页面元素和相应数据以及适配器
        for (i in 0 until titles.size) {
            initAdapter()
        }
        initPager()
        refreshCurrentPage()
    }

    override fun setBean(bean: String) {
        this.bean = bean
        if (dialog != null) {
            dialog!!.setBean(bean)
        }
    }

    override fun loadGameItemList(currentPage: Int, list: ArrayList<ESportItemBean>) {
        holders[currentPage].refreshLayout.finishRefresh(true)
        guesses[currentPage].clear()

        if (list != null && !list.isEmpty()) {
            guesses[currentPage].addAll(list)
        }
        adapters[currentPage].notifyDataSetChanged()
    }

    /**
     * 去充值
     */
    override fun gotoRecharge() {
        var intent = Intent(this, RechargeActivity::class.java)
        startActivityForResult(intent, REQUEST_RECHARGE)
    }

    /**
     * 点击选择获胜队伍
     */
    override fun onTeamClick(eSportItemBean: ESportItemBean, eSportItemSelectBean: ESportItemSelectBean) {
        var currentPage = vp_content.currentItem
        if (dialog != null) {
            dialog!!.dismiss()
        }
        dialog = OrderDialog(this)
        dialog!!.builder()
                .setData(eSportItemBean, eSportItemSelectBean)
                .setPageTitle(titles[currentPage])
                .setBean(bean)
                .setListener(this)
                .setActionConfirm("确定").show()
    }

    /**
     * 当提交投注数量为空时，调用
     */
    override fun showTips(tips: String) {
        showToast(tips)
    }

    /**
     * 当提交投注数量余额不足时，调用
     */
    override fun showDialog() {
        return AlertDialog.Builder(this)
                .setTitle("提示！")
                .setMessage("当前账户余额不足，是否充值")
                .setPositiveButton("去充值") { _, _ ->
                    startActivity(Intent(this, RechargeActivity::class.java))
                }
                .setNegativeButton("取消") { _, _ -> }.create().show()
    }

    /**
     * 点击提交订单
     */
    override fun onOrderConfirmClick(bean: ESportItemBean, teamValue: String, payAmount: String) {
        // 判断是否已经登录
        if (loginBean == null) {
            startActivity(Intent(this, LoginActivity::class.java))
            return
        }

        var params = HashMap<String, String>()
        var betList = ArrayList<ESportOrderBean>()
        var eSportOrderBean = ESportOrderBean()

        eSportOrderBean.redNum = teamValue
        eSportOrderBean.playType = bean.playId!!
        eSportOrderBean.period = bean.matchId!!
        betList.add(eSportOrderBean)

        params["userId"] = loginBean!!.userId ?: ""
        params["lotteryId"] = "10"
        params["period"] = bean.matchId!!
        params["buyWay"] = "0"
        params["payAmount"] = payAmount
        params["betNum"] = "1"
        params["betTimes"] = "1"
        params["betBunch"] = "1-1"
        params["orderBetJson"] = betList.json()
        params["isPublishFollow"] = "1"

        eSportDetailPresenter.postOrder(params)
    }

    override fun toPay(orderResp: OrderResp) {
        showToast("预测成功")
        if (dialog != null) {
            dialog!!.dismiss()
        }
        if (loginBean != null) {
            eSportDetailPresenter.getWindowList(loginBean!!.userId!!)
            eSportDetailPresenter.getUserInfo(loginBean!!.userId!!)
        }
    }

    override fun setWindowList(list: List<WindowBean>) {
        // type 类型 1-中奖；2-邀请首单；3-邀请首冲；4-每日首单；5-新用户注册
        for (i in list.size - 1 downTo 0) {
            when (list[i].type) {
                "1" -> {
                    PrizeDialog(this)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(this, if (loginBean == null) LoginActivity::class.java else OrderListActivity::class.java)) }
                            .show()
                }
                "6" -> {
                    PrizeDialog(this)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(this, if (loginBean == null) LoginActivity::class.java else MyPredictionActivity::class.java)) }
                            .show()
                }
                else -> {
                    RewardDialog(this)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("确定")
                            .show()
                }
            }
        }
    }

    /**
     * 绑定支付宝
     */
    override fun bindAlipay() {
        AlertDialog.Builder(context())
                .setTitle("温馨提示").setMessage("为了账户安全，请绑定支付宝")
                .setNegativeButton("取消") { dialog, _ ->
                    dialog.dismiss()
                }.setPositiveButton("确定") { dialog, _ ->
                    alipayPresenter.auth4alipay()
                }.setCancelable(false)
                .create().show()
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
        eSportDetailPresenter.bindAlipay(APP.get()!!.loginInfo!!.userId!!, authData)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_RECHARGE && loginBean != null) {
            eSportDetailPresenter.getUserInfo(loginBean!!.userId!!)
        }
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onDestroy() {
        super.onDestroy()
        alipayPresenter.detachView()
        eSportDetailPresenter.detachView()
        if (dialog != null) {
            dialog!!.dismiss()
        }
    }
}
